# -*- coding: utf-8 -*-
import random
import scrapy
from datetime import datetime
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from zc_core.dao.spu_pool_dao import SpuPoolDao
from zc_core.model.items import Box
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter
from fjzfcg.rules import parse_item_data
from zc_core.spiders.base import BaseSpider


class FullSpider(BaseSpider):
    name = 'full'

    # 常用链接
    item_url = 'http://120.35.30.176/shopping/goods.htm?id={}'
    order_url = 'http://120.35.30.176/shopping/newgoodsorder.htm'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)
        # 订单明细每页条数
        self.page_size = 8

    def start_requests(self):
        settings = get_project_settings()
        pool_list = SpuPoolDao().get_spu_pool_list()
        self.logger.info('全量：%s' % (len(pool_list)))
        random.shuffle(pool_list)
        for spu in pool_list:
            spu_id = spu.get('_id')
            offline_time = spu.get('offlineTime', 0)
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', spu_id, offline_time)
                continue
            # 避免重复采集
            if self.done_filter.contains(spu_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', spu_id)
                continue

            # 采集商品关联关系
            yield Request(
                method='POST',
                url=self.item_url.format(spu_id),
                callback=self.parse_item_data,
                errback=self.error_back,
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'spuId': spu_id,
                },
                headers={
                    'Connection': 'keep-alive',
                    'Cache-Control': 'max-age=0',
                    'Upgrade-Insecure-Requests': '1',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3730.400 QQBrowser/10.5.3805.400',
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Accept-Encoding': 'gzip, deflate',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                },
            )

    # 处理ItemData
    def parse_item_data(self, response):
        meta = response.meta
        spu_id = meta.get('spuId')
        data_list = parse_item_data(response)
        if data_list:
            self.logger.info('同款: spu=%s, cnt=%s' % (spu_id, len(data_list)))
            yield Box('item', self.batch_no, data_list)
        else:
            self.logger.error('下架: [%s]' % spu_id)
